#include "instances.h"
#include "globals.h"
#include "map.h"
#include "clientbattle.h"
#include "serverbattle.h"

// Constructor
InstanceClass::InstanceClass() 
{

}

// Destructor
InstanceClass::~InstanceClass() 
{
	// Delete maps
	for(MapIterator = Maps.begin(); MapIterator != Maps.end(); ++MapIterator) 
	{
		delete *MapIterator;
	}

	Maps.clear();

	// Delete battles
	for(BattleIterator = Battles.begin(); BattleIterator != Battles.end(); ++BattleIterator) 
	{
		delete *BattleIterator;
	}
	Battles.clear();
}

// Updates all the instances
void InstanceClass::Update(u32 TDeltaTime) 
{
	// Update maps
	for(MapIterator = Maps.begin(); MapIterator != Maps.end(); ++MapIterator) 
	{
		(*MapIterator)->Update(TDeltaTime);
	}

	// Update battles
	for(BattleIterator = Battles.begin(); BattleIterator != Battles.end(); ++BattleIterator) 
	{
		(*BattleIterator)->Update(TDeltaTime);
	}
}

// Gets a map from the manager. Loads the level if it doesn't exist
CGMap *InstanceClass::GetMap(int TMapID) 
{
	// Loop through loaded maps
	for(MapIterator = Maps.begin(); MapIterator != Maps.end(); ++MapIterator) 
	{
		// Check id
		if((*MapIterator)->GetID() == TMapID)
			return (*MapIterator);
	}

	// Not found, so create it
	CGMap *NewMap = new CGMap(TMapID);
	Maps.push_back(NewMap);

	return NewMap;
}

// Create a client battle instance
ClientBattleClass *InstanceClass::CreateClientBattle() 
{
	ClientBattleClass *NewBattle = new ClientBattleClass();
	Battles.push_back(NewBattle);

	return NewBattle;
}

// Create a server battle instance
ServerBattleClass *InstanceClass::CreateServerBattle() 
{
	ServerBattleClass *NewBattle = new ServerBattleClass();
	Battles.push_back(NewBattle);

	return NewBattle;
}

// Battle has finished and can be removed
void InstanceClass::DeleteBattle(BattleClass *TBattle) 
{
	// Loop through loaded battles
	for(BattleIterator = Battles.begin(); BattleIterator != Battles.end(); ++BattleIterator) 
	{
		if(*BattleIterator == TBattle) 
		{
			Battles.erase(BattleIterator);
			delete TBattle;
			break;
		}
	}
}
